package com.z.controller;

import com.z.pojo.Cart;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@WebServlet("/addCart")
public class AddCartServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String gid = req.getParameter("gid");
        String gname = req.getParameter("gname");
        String g_img = req.getParameter("g_img");
        String price = req.getParameter("price");
        String num = req.getParameter("num");


        Cart cart = new Cart(Integer.valueOf(gid),gname,g_img,Double.valueOf(price),Integer.valueOf(num));

        Map<Integer,Cart> carts = (Map<Integer, Cart>) req.getSession().getAttribute("carts");



        if(carts ==null||"".equals(carts)){
            carts  = new HashMap<>();
            carts.put(cart.getGid(),cart);
        }else{
            if(carts.containsKey(cart.getGid())){
                Cart cart1 = carts.get(cart.getGid());
                cart.setNum(cart1.getNum()+cart.getNum());
                carts.put(cart.getGid(),cart);
            }else{
                carts.put(cart.getGid(),cart);
                carts.forEach((k,v)-> System.out.println(k+":"+v));
            }
        }
        req.getSession().setAttribute("carts",carts);
        resp.sendRedirect(req.getContextPath()+"/order.jsp");
    }

}
